package com.ireprot.demo.reportview;
import com.itextpdf.text.pdf.codec.Base64;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.HtmlResourceHandler;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.export.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class ReportUtil {

    private  static final  String DEFAULT_EXPORT_NAME = "报表";
        /**
         * 以html的形式打印报表
         *
         * @param response
         * @param jasperPrint 打印对象
         * @throws Exception
         */
        public static void exportHtml(HttpServletResponse response, JasperPrint jasperPrint) throws Exception {
            response.setContentType("text/html");//以页面的形式打开

            Map<String, String> images = new HashMap<>();
            HtmlExporter exporter=new HtmlExporter();
            String[] propertyNames = jasperPrint.getPropertyNames();
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
            // exporter.setExporterOutput(new SimpleHtmlExporterOutput(response.getOutputStream()));
            SimpleHtmlReportConfiguration simpleHtmlReportConfiguration  = new SimpleHtmlReportConfiguration();
            //将svg转换成img(png)格式
            simpleHtmlReportConfiguration.setConvertSvgToImage(true);
            SimpleHtmlExporterConfiguration reportExportConfiguration =new SimpleHtmlExporterConfiguration();
            exporter.setConfiguration(reportExportConfiguration );
            exporter.setConfiguration(simpleHtmlReportConfiguration);
            //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ServletOutputStream outputStream = response.getOutputStream();
            SimpleHtmlExporterOutput simpleHtmlExporterOutput = new SimpleHtmlExporterOutput(response.getOutputStream());
            //生成imgsrc为base64格式的资源
            simpleHtmlExporterOutput.setImageHandler(new HtmlResourceHandler() {
                @Override
                public void handleResource(String id, byte[] data) {
                    images.put(id, "data:image/png;base64," + Base64.encodeBytes(data));
                }

                @Override
                public String getResourcePath(String id) {
                    return images.get(id);
                }
            });
            exporter.setExporterOutput(simpleHtmlExporterOutput);
            exporter.exportReport();
            outputStream.flush();
        }




    /**
     * 以html的形式打印报表
     *
     * @param response
     * @param jasperPrint 打印对象
     * @throws Exception
     */
    public static void exportPdf(HttpServletResponse response, JasperPrint jasperPrint) throws Exception {
        //设置导出文件格式
        response.setContentType("application/pdf");
        String filename = "";
        //设置导出文件名称
        filename = new String(DEFAULT_EXPORT_NAME.getBytes("GBK"),"ISO8859_1");
        response.setHeader("Content-Disposition", "attachment;filename="+filename+".pdf");
        //导出pdf
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        SimplePdfReportConfiguration configuration = new SimplePdfReportConfiguration();
        exporter.setConfiguration(configuration);
        // 配置导出属性
        SimplePdfExporterConfiguration  simpleExporterConfiguration = new SimplePdfExporterConfiguration();
        simpleExporterConfiguration.setCreatingBatchModeBookmarks(true);
        exporter.exportReport();
        response.flushBuffer();
    }

        /**
          * 导出excel
          */
       public static void exportExcel(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException {

                response.setContentType("application/vnd.ms-excel");
                String defaultname=null;
                if(defaultFilename.trim()!=null&&defaultFilename!=null){
                    defaultname=defaultFilename+".xls";
                }else{
                       defaultname="export.xls";
                }
                String fileName = new String(defaultname.getBytes("gbk"), "utf-8");
                response.setHeader("Content-disposition", "attachment; filename="+ fileName);
                ServletOutputStream ouputStream = response.getOutputStream();
                JRXlsExporter exporter = new JRXlsExporter();
               exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
               exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream));
               SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
               configuration.setOnePagePerSheet(true);
               configuration.setDetectCellType(true);
               configuration.setCollapseRowSpan(false);
               exporter.setConfiguration(configuration);
                exporter.exportReport();
                ouputStream.flush();
                ouputStream.close();
    }
    /**
     * 导出excel
     */
    public static void exportWord(JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException {

        response.setContentType("application/vnd.ms-excel");
        String defaultname=null;
        if(defaultFilename.trim()!=null&&defaultFilename!=null){
            defaultname=defaultFilename+".docx";
        }else{
            defaultname="export.docx";
        }
        String fileName = new String(defaultname.getBytes("gbk"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="+ fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        JRDocxExporter exporter = new JRDocxExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream));
        SimpleDocxReportConfiguration configuration = new SimpleDocxReportConfiguration();
        exporter.setConfiguration(configuration);
        //导出
        SimpleDocxExporterConfiguration reportExportConfiguration =new SimpleDocxExporterConfiguration();
        exporter.setConfiguration(reportExportConfiguration);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }



    /**
     * 创建 JasperReport 对象
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static JasperReport createJasperReport(InputStream inputStream) throws Exception {
        JasperReport jasperReport;

//        if (reportModel.getType() == 1) {
            //编译，并得到jasperReport对象，相当于.jasper文件
            jasperReport = JasperCompileManager.compileReport(inputStream);
//        } else {
//            //直接加载编译后的模板文件
//            jasperReport = (JasperReport) JRLoader.loadObject(new ByteArrayInputStream(reportModel.getFileByte()));
//        }
        return jasperReport;
    }


}
